import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

class XmmWebPage extends StatefulWidget {

  const XmmWebPage({super.key});

  @override
  State<XmmWebPage> createState() => XmmWebPageState();
}

class XmmWebPageState extends State<XmmWebPage> {
  late WebViewController controller;

  final _title = "".obs;

  String? url;

  @override
  void initState() {
    super.initState();

    url = Get.arguments;

    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            //
          },
          onPageStarted: (String url) {
            //
          },
          onPageFinished: (String url) {
            controller.getTitle().then((value) => _title.value = value ?? '');
          },
          onWebResourceError: (WebResourceError error) {
            //
          },
          onNavigationRequest: (NavigationRequest request) {
            if (request.url.startsWith('https://www.youtube.com/')) {
              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(Uri.parse(url ?? ""));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Obx(() => Text(
          _title.value,
          style: const TextStyle(color: Colors.black),
        )),
        backgroundColor: Colors.white,
        leading: CupertinoButton(
          onPressed: () {
            onEventBack();
          },
          child: const Icon(Icons.arrow_back, color: Colors.black),
        ),
      ),
      body: WebViewWidget(controller: controller),
    );
  }

  /// Events
  void onEventBack() async {
    if (await controller.canGoBack()) {
      controller.goBack();
    } else {
      Get.back();
    }
  }
}
